package com.vcolco.utils;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.Base64;

/**
 * Created by fengwei.cfw on 2017/3/6.
 */
public class FileUtil {

    /**
     * 获得指定文件的byte数组
     */
    public static byte[] getBytes(File file) {
        byte[] buffer = null;
        try {
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }

    public static byte[] getBytes(MultipartFile file) {
        byte[] buffer = null;
        try {
            InputStream fis = file.getInputStream();
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }

    /**
     * 保存文件至指定路径
     *
     * @param request
     * @param fileBytes
     * @param suffix
     * @return
     */
    public static String saveFileByBytes(HttpServletRequest request, byte[] fileBytes, String name, String suffix) {
        String fileName = name + "." + suffix;
        try {
            String temporaryPath = request.getServletContext().getRealPath("");
            File temporaryFolder = new File(temporaryPath);
            File temporaryFile = new File(temporaryFolder, fileName);
            if (temporaryFile.exists()) {
                temporaryFile.delete();
            }
            temporaryFile.createNewFile();
            FileOutputStream os = new FileOutputStream(temporaryFile);
            InputStream is = new ByteArrayInputStream(fileBytes);
            int b = 0;
            while ((b = is.read()) != -1) {
                os.write(b);
            }
            os.flush();
            os.close();
            is.close();
            String filePath = temporaryFile.getPath();
            return filePath;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static void byte2File(byte[] buf, String filePath, String fileName) {
        if (buf == null) {
            return;
        }
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            File dir = new File(filePath);
            if (!dir.exists() && dir.isDirectory()) {
                dir.mkdirs();
            }
            file = new File(filePath + File.separator + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(buf);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static String getFileExtName(String name) {
        String extName = null;
        if (name != null && name.contains(".")) {
            extName = name.substring(name.lastIndexOf(".") + 1);
        }
        return extName;
    }

    public static void deleteFile(String filePath) {
        File temporaryFile = new File(filePath);
        if (temporaryFile.exists()) {
            temporaryFile.delete();
        }
    }

    /**
     * base64转byte数组
     *
     * @param base64
     * @return
     */
    public static byte[] base64ToBytes(String base64) {
        return Base64.getDecoder().decode(base64);
    }

    /**
     * byte[]转字符串
     *
     * @param buff
     * @return
     */
    public String byteToHex(byte[] buff) {
        String returnStr = "";
        try {
            String hexStr = "";
            String hexDic = "0123456789abcdef";
            //将byte转换成hex十六进制
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < buff.length; i++) {
                int tmp = buff[i] & 0XFF;
                String str = Integer.toHexString(tmp);
                if (str.length() == 1) {
                    sb.append("0" + str);
                } else {
                    sb.append(str);
                }
            }
            hexStr = sb.toString();
            //将hex十六进制转换成字符串
            char[] hexArray = hexStr.toCharArray();
            byte[] bytes = new byte[hexStr.length() / 2];
            int n;
            for (int i = 0; i < bytes.length; i++) {
                n = hexDic.indexOf(hexArray[2 * i]) * 16;
                n += hexDic.indexOf(hexArray[2 * i + 1]);
                bytes[i] = (byte) (n & 0xff);
            }
            returnStr = new String(bytes);
            return returnStr;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return returnStr;
    }
}
